package com.ruoyi.web.controller.system

import com.ruoyi.common.constant.Constants
import com.ruoyi.common.core.domain.AjaxResult
import com.ruoyi.common.core.domain.entity.SysUser
import com.ruoyi.common.core.domain.model.LoginBody
import com.ruoyi.common.utils.SecurityUtils
import com.ruoyi.framework.web.service.SysLoginService
import com.ruoyi.framework.web.service.SysPermissionService
import com.ruoyi.system.service.ISysMenuService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
open class SysLoginController {
    @Autowired
    private lateinit var loginService: SysLoginService

    @Autowired
    private lateinit var menuService: ISysMenuService

    @Autowired
    private lateinit var permissionService: SysPermissionService

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    open  fun login(@RequestBody loginBody: LoginBody): AjaxResult {
        val ajax: AjaxResult = AjaxResult.success()
        // 生成令牌
        val token: String = loginService.login(
            loginBody.username, loginBody.password, loginBody.code,
            loginBody.uuid
        )
        ajax[Constants.TOKEN] = token
        return ajax
    }

    @get:GetMapping("getInfo")
    open val info: AjaxResult
        /**
         * 获取用户信息
         *
         * @return 用户信息
         */
        get() {
            val user: SysUser = SecurityUtils.loginUser.user!!
            // 角色集合
            val roles: Set<String> = permissionService.getRolePermission(user)
            // 权限集合
            val permissions: Set<String> = permissionService.getMenuPermission(user)
            val ajax: AjaxResult = AjaxResult.success()
            ajax["user"] = user
            ajax["roles"] = roles
            ajax["permissions"] = permissions
            return ajax
        }

    @get:GetMapping("getRouters")
    open val routers: AjaxResult
        /**
         * 获取路由信息
         *
         * @return 路由信息
         */
        get() {
            val userId: Long = SecurityUtils.userId
            val menus = menuService.selectMenuTreeByUserId(userId)
            return AjaxResult.success(menuService.buildMenus(menus))
        }
}
